<template>
  <el-card class='questions-container'>
    <el-row type="flex" justify="space-between">
      <el-col>
        <span class="text-color">说明：目前支持学科和关键字条件筛选</span>
      </el-col>
      <el-col>
        <el-row type="flex" justify="end">
          <el-button @click="addNewQuestion" type="success" icon="el-icon-edit" size="small">新增试题
          </el-button>
        </el-row>
      </el-col>
    </el-row>
    <el-row class="opt-margin">
      <el-form ref="questionFormRef" :model="questionForm" label-width="80px">
        <el-row type="flex" justify="space-between" align="center">
          <el-col>
            <el-form-item label="学科" prop="subjectID">
              <el-select size="small" v-model="questionForm.subjectID" placeholder="请选择"
                class="cascader-width">
                <el-option v-for="item in subjectList" :key="item.value" :label="item.label"
                  :value="item.value">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col>
            <el-form-item label="二级目录" prop="catalogID">
              <el-select @focus="handlersecondCatalog" size="small" v-model="questionForm.catalogID"
                placeholder="请选择" class="cascader-width">
                <el-option v-for="item in secondCatalog" :key="item.value" :label="item.label"
                  :value="item.value">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col>
            <el-form-item label="标签" prop="tags">
              <el-select @focus="handlersubjectLabel" size="small" v-model="questionForm.tags"
                placeholder="请选择" class="cascader-width">
                <el-option v-for="item in tags" :key="item.value" :label="item.label"
                  :value="item.label">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col>
            <el-form-item label="关键字" prop="keyword">
              <el-input size="small" v-model="questionForm.keyword" placeholder="根据题干搜索"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row type="flex" justify="space-between" align="center">
          <el-col>
            <el-form-item label="试题类型" prop="questionType">
              <el-select size="small" v-model="questionForm.questionType" placeholder="请选择"
                class="cascader-width">
                <el-option v-for="item in questionType" :key="item.value" :label="item.label"
                  :value="item.value">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col>
            <el-form-item label="难度" prop="difficulty">
              <el-select size="small" v-model="questionForm.difficulty" placeholder="请选择"
                class="cascader-width">
                <el-option v-for="item in difficulty" :key="item.value" :label="item.label"
                  :value="item.value">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col>
            <el-form-item label="方向" prop="direction">
              <el-select size="small" v-model="questionForm.direction" placeholder="请选择"
                class="cascader-width">
                <el-option v-for="item in direction" :key="item.value" :label="item.label"
                  :value="item.value">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col>
            <el-form-item label="录入人" prop="creatorID">
              <el-select size="small" v-model="questionForm.creatorID" placeholder="请选择"
                class="cascader-width">
                <el-option v-for="item in creator" :key="item.value" :label="item.label"
                  :value="item.value">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row type="flex" justify="space-between" align="center">
          <el-col>
            <el-form-item label="题目备注" prop="remarks">
              <el-input size="small" v-model="questionForm.remarks"></el-input>
            </el-form-item>
          </el-col>
          <el-col>
            <el-form-item label="企业简称" prop="shortName">
              <el-input size="small" v-model="questionForm.shortName"></el-input>
            </el-form-item>
          </el-col>
          <el-col>

            <el-form-item label="城市" prop="province">
              <el-row type="flex" justify="space-between">
                <el-col>

                  <el-select size="small" v-model="questionForm.province" placeholder="请选择"
                    @change="choseProvince">
                    <el-option v-for="item in province" :key="item.value" :label="item.label"
                      :value="item.value">
                    </el-option>
                  </el-select>

                </el-col>
                <el-col class="city-margin">
                  <el-form-item prop="city">
                    <el-select size="small" v-model="questionForm.city" placeholder="请选择">
                      <el-option v-for="item in citys" :key="item.value" :label="item.label"
                        :value="item.value">
                      </el-option>
                    </el-select>

                  </el-form-item>
                </el-col>
              </el-row>
            </el-form-item>

          </el-col>
          <el-col>
            <el-row type="flex" justify="end">
              <el-button type="default" size="mini" @click="resetQuestionForm">清除</el-button>
              <el-button type="primary" size="mini" @click="searchQuestions">搜索</el-button>
            </el-row>
          </el-col>
        </el-row>
      </el-form>
    </el-row>
    <el-alert :title="'数据一共'+count+'条'" type="info" show-icon :closable="false">
    </el-alert>
    <!--   table 题库表格 -->
    <el-table class="table-margin" :data="tableQuestionsData" style="width: 100%">
      <el-table-column prop="number" label="试题编号" width="120">
      </el-table-column>
      <el-table-column prop="subject" label="学科" width="180">
      </el-table-column>
      <el-table-column prop="catalog" label="目录" width="180">
      </el-table-column>
      <el-table-column label="题型" width="180">
        <template v-slot="{row}">
          <span v-if="row.questionType === '1'">单选</span>
          <span v-else-if="row.questionType === '2'">多选</span>
          <span v-else>简答</span>
        </template>
      </el-table-column>
      <el-table-column label="题干" width="280">
        <template v-slot="{row}">
          <span v-html="row.question"></span>
        </template>
      </el-table-column>
      <el-table-column label="录入时间" width="180">
        <template v-slot="{row}">
          <span>{{ row.addDate | parseTime }}</span>
        </template>
      </el-table-column>
      <el-table-column label="难度" width="180">
        <template v-slot="{row}">
          <span v-if="row.difficulty === '1'">简单</span>
          <span v-else-if="row.difficulty === '2'">一般</span>
          <span v-else>困难</span>
        </template>
      </el-table-column>
      <el-table-column prop="creator" label="录入人" width="180">
      </el-table-column>
      <el-table-column label="操作" width="180">
        <template v-slot="{ row }">
          <el-tooltip class="item" effect="light" :open-delay="500" content="预览" placement="bottom-end"
            :visible-arrow="false">
            <el-button @click="preview(row)" size="small" type="primary" icon="el-icon-view" plain
              circle></el-button>
          </el-tooltip>
          <el-tooltip class="item" effect="light" :open-delay="500" content="修改" placement="bottom-end"
            :visible-arrow="false">
            <el-button @click="editNewQuestion(row.id)" size="small" type="success"
              icon="el-icon-edit" plain circle></el-button>
          </el-tooltip>
          <el-tooltip class="item" effect="light" :open-delay="500" content="删除" placement="bottom-end"
            :visible-arrow="false">
            <el-button @click="deleteQuestion(row.id)" size="small" type="danger"
              icon="el-icon-delete" plain circle></el-button>
          </el-tooltip>
          <el-tooltip class="item" effect="light" :open-delay="500" content="加入精选" placement="bottom-end"
            :visible-arrow="false">
            <el-button @click="addChoiceQuestion(row.id)" size="small" type="warning"
              icon="el-icon-check" plain circle></el-button>
          </el-tooltip>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination class="pagination-position" background @size-change="handleQuestionsSizeChange"
      @current-change="handleQuestionsCurrentChange" :current-page="questionForm.page"
      :page-sizes="[5, 10, 20, 50]" :page-size="questionForm.pagesize"
      layout=" prev, pager, next,sizes,jumper" :total="count">
    </el-pagination>
    <Preview ref="previewDialogRef" :previewDialogVisibleShow.sync="previewDialogVisibleShow" />
  </el-card>
</template>

<script>
import { difficulty, direction, questionType } from '@/api/hmmm/constants'
import { list, remove, choiceAdd } from '@/api/hmmm/questions'
import { simple } from '@/api/hmmm/subjects'
import { simple as directorysSimpleList } from '@/api/hmmm/directorys'
import { simple as userSimpleList } from '@/api/base/users'
import { simple as tagsSimpleList } from '@/api/hmmm/tags'
import { provinces, citys } from '@/api/hmmm/citys'
import Preview from '../components/questions-preview.vue'
import { parseTime } from '@/utils'
export default {
  name: 'Questions',
  data () {
    return {
      questionForm: {
        page: 1,
        pagesize: 5,
        subjectID: '',
        catalogID: '',
        tags: '',
        keyword: '',
        questionType: '',
        difficulty: '',
        direction: '',
        creatorID: '',
        remarks: '',
        shortName: '',
        province: '',
        city: ''
      },
      subjectList: [],
      secondCatalog: [],
      tags: [],
      questionType,
      difficulty,
      direction,
      creator: [],
      province: [],
      citys: [],
      tableQuestionsData: [],
      count: 0,
      previewDialogVisibleShow: false
    }
  },
  created () {
    this.loadingQuestionsList()
    this.loadingSubject()
    this.loadingDirection()
    this.loadingUserList()
    this.loadingProvinceList()
  },
  components: {
    Preview
  },
  filters: {
    parseTime
  },
  methods: {
    // 加载问题列表
    async loadingQuestionsList () {
      try {
        const { data } = await list(this.handlerPaginationData())
        // console.log(data)
        this.count = data.counts
        this.tableQuestionsData = data.items
      } catch (error) {
        this.$message.error('获取列表数据失败')
      }
    },
    // 处理问题尺寸改变
    handleQuestionsSizeChange (newSize) {
      this.questionForm.pagesize = newSize
      this.loadingQuestionsList()
    },
    // 处理页面变化
    handleQuestionsCurrentChange (newPage) {
      this.questionForm.page = newPage
      this.loadingQuestionsList()
    },
    // 处理分页请求数据过多问题
    handlerPaginationData () {
      const newQuestionForm = {}
      for (const key in this.questionForm) {
        if (this.questionForm[key]) {
          newQuestionForm[key] = this.questionForm[key]
        }
      }
      return newQuestionForm
    },
    // 加载学科列表
    async loadingSubject () {
      try {
        const { data } = await simple()
        this.subjectList = data
      } catch (error) {
        this.$message.error('加载学科列表失败')
      }
    },
    // 处理二级目录
    async handlersecondCatalog () {
      try {
        if (this.questionForm.subjectID || this.questionForm.subjectID === 0) {
          const { data } = await directorysSimpleList({
            subjectID: this.questionForm.subjectID
          })
          this.secondCatalog = data
        }
      } catch (error) {
        this.$message.error('失败')
      }
    },
    // 处理学科标签
    async handlersubjectLabel () {
      try {
        if (this.questionForm.subjectID || this.questionForm.subjectID === 0) {
          const { data } = await tagsSimpleList({
            subjectID: this.questionForm.subjectID
          })
          // console.log(data)
          this.tags = data
        }
      } catch (error) {
        this.$message.error('加载标签列表失败')
      }
    },
    // 处理方向
    loadingDirection () {
      this.direction = this.direction.map((item) => {
        return {
          value: item,
          label: item
        }
      })
    },
    // 加载录入人列表
    async loadingUserList () {
      try {
        const { data } = await userSimpleList()
        // console.log(data)
        this.creator = data.map((item) => {
          return {
            value: item.id,
            label: item.username
          }
        })
      } catch (error) {
        this.$message.error('获取录入人失败')
      }
    },
    // 加载省份列表
    loadingProvinceList () {
      this.province = provinces().map((item) => {
        return {
          value: item,
          label: item
        }
      })
    },
    // 选择城市
    choseProvince (val) {
      this.questionForm.city = ''
      this.citys = citys(val).map((item) => {
        return {
          value: item,
          label: item
        }
      })
    },
    // 重置表单
    resetQuestionForm () {
      this.$refs.questionFormRef.resetFields()
    },
    // 搜索
    searchQuestions () {
      this.questionForm.page = 1
      this.loadingQuestionsList()
    },
    // 预览
    preview (row) {
      // console.log(row)
      this.$refs.previewDialogRef.loadingPreviewList(row.id)
      this.previewDialogVisibleShow = true
    },
    // 删除题目
    async deleteQuestion (id) {
      try {
        const res = await this.$confirm('此操作将永久删除该题目, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).catch((err) => err)
        if (res !== 'confirm') {
          return this.$message.info('已取消删除该题目')
        }
        if (this.tableQuestionsData.length === 1) {
          this.questionForm.page = this.questionForm.page === 1 ? 1 : this.questionForm.page - 1
        }
        await remove({ id })
        this.$message.success('删除题目成功')
        this.loadingQuestionsList()
      } catch (error) {
        this.$message.error('删除题目失败！')
      }
    },
    // 新增试题
    addNewQuestion () {
      this.$router.push({
        name: 'questions-new'
      })
    },
    // 编辑试题录入
    editNewQuestion (id) {
      // console.log(id)
      this.$router.push({
        name: 'questions-new',
        query: {
          id
        }
      })
    },
    // 加入到精选题库
    async addChoiceQuestion (id) {
      try {
        const res = await this.$confirm('此操作将该题目加入精选, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'info'
        }).catch((err) => err)
        if (res !== 'confirm') {
          return this.$message.info('已取消将该题目加入精选')
        }
        await choiceAdd({ id, choiceState: 1 })
        this.$message.success('将该题目加入精选成功')
        this.loadingQuestionsList()
      } catch (error) {
        this.$message.error('将该题目加入精选失败！')
      }
    }
  }
}
</script>

<style scoped lang='less'>
* {
  box-sizing: border-box;
}
.questions-container {
  margin: 10px;
  .text-color {
    color: #ffc0cb;
    font-size: 12px;
  }
  .opt-margin {
    margin-top: 15px;
    /deep/.el-form-item--medium {
      margin-left: unset;
    }
    .cascader-width {
      width: 100%;
    }
  }
  .table-margin {
    margin: 15px 0;
  }
  .el-form-item {
    margin-bottom: 18px;
  }
  .city-margin {
    margin-left: 8px;
  }
  .pagination-position {
    text-align: right;
    /deep/.el-pagination__jump {
      margin-left: unset;
    }
  }
}
</style>
